# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re

from mathruler.grader import extract_boxed_content, grade_answer


def format_reward(predict_str: str) -> float:
    pattern = re.compile(r"<think>.*</think>.*\\boxed\{.*\}.*", re.DOTALL)
    match_result = re.fullmatch(pattern, predict_str)
    return 10.0 if match_result else 0.0


def acc_reward(predict_str: str, ground_truth: str, use_boxed: bool = True) -> float:
    if use_boxed:
        answer = extract_boxed_content(predict_str)
    else:
        answer = predict_str
    return 10.0 if grade_answer(answer, ground_truth) else 0.0
    

def check_keywords(input_str):
    """
    检查输入字符串中是否包含指定关键词列表中的任何一个词
    
    参数:
        input_str: 待检查的字符串
        
    返回:
        1: 如果包含任何关键词
        0: 如果不包含任何关键词
    """
    # 定义需要检查的关键词列表
    keywords = ["掘进机", "巷道尽头", "圆柱", "网", "杆", "钻机", "人"]
    
    score = 0
    # 检查每个关键词是否在输入字符串中
    for keyword in keywords:
        if keyword in input_str:
            # return 1
            score += 1
    
    # 如果没有找到任何关键词，返回0
    return score

def compute_score(predict_str: str, ground_truth: str, use_boxed: bool = True, format_score: float = 0.1) -> float:
    return (1.0 - format_score) * acc_reward(predict_str, ground_truth, use_boxed) + format_score * format_reward(
        predict_str
    ) + check_keywords(predict_str)



# 示例用法
if __name__ == "__main__":
    test_strings = [
        "这是一台掘进机",
        "工人正在操作钻机",
        "巷道尽头有一个圆柱",
        "这个网络很稳定",
        "这里有一根杆",
        "天空很蓝",
        "人们在工作"
    ]
    
    for s in test_strings:
        result = check_keywords(s)
        print(f"字符串: '{s}' -> 结果: {result}")
    
